<template>
  <div class="wechat-payment">
    <!-- 支付弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="400px"
      center
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <div class="payment-content">
        <!-- 套餐信息 -->
        <div class="package-info">
          <div class="package-name">{{ packageInfo.name }}</div>
          <div class="package-price">¥ {{ packageInfo.price }}</div>
        </div>
        
        <!-- 支付状态提示 -->
        <div v-if="paymentStatus.message" :class="['payment-status', paymentStatus.success ? 'success' : 'error']">
          <el-icon v-if="paymentStatus.success"><Check /></el-icon>
          <el-icon v-else><Close /></el-icon>
          <span>{{ paymentStatus.message }}</span>
        </div>
        
        <!-- 二维码支付 -->
        <div v-if="qrCodeUrl" class="qr-code-container">
          <p>请使用微信扫一扫下面的二维码进行支付</p>
          <div class="qr-code">
            <img :src="qrCodeImageUrl" alt="微信支付二维码" />
          </div>
        </div>
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="confirmPayment" :loading="loading">
            {{ loading ? '处理中...' : '确认支付' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
    
    <!-- 加载提示 -->
    <div v-if="loading && !dialogVisible" class="loading-overlay">
      <div class="loading-spinner">
        <el-icon><Loading /></el-icon>
        <span>{{ loadingText }}</span>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onBeforeUnmount } from 'vue';
import { ElMessage } from 'element-plus';
import { Loading, Check, Close } from '@element-plus/icons-vue';
import { rechargePackage, checkOrderStatus } from '@/api/chat';

// 组件属性定义
const props = defineProps({
  // 弹窗标题
  title: {
    type: String,
    default: '微信支付'
  },
  // 套餐信息
  packageInfo: {
    type: Object,
    default: () => ({ type: '', name: '默认套餐', price: 0 })
  }
});

// 组件事件
const emit = defineEmits(['success', 'cancel', 'error', 'close']);

// 组件状态
const dialogVisible = ref(false);
const loading = ref(false);
const loadingText = ref('正在处理支付请求...');
const paymentStatus = ref({ success: false, message: '' });
const qrCodeUrl = ref('');
const orderSn = ref('');

// 轮询相关变量
const orderTimer = ref(null);
const MAX_CHECK_TIMES = 20;
const checkTimes = ref(0);

// 计算属性：二维码图片URL
const qrCodeImageUrl = computed(() => {
  if (!qrCodeUrl.value) return '';
  return `https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrCodeUrl.value)}`;
});

// 打开支付弹窗
const showPayment = () => {
  dialogVisible.value = true;
  // 重置状态
  paymentStatus.value = { success: false, message: '' };
  qrCodeUrl.value = '';
  orderSn.value = '';
  checkTimes.value = 0;
};

// 关闭弹窗
const handleClose = () => {
  stopOrderCheck();
  dialogVisible.value = false;
  emit('close');
};

// 确认支付
const confirmPayment = async () => {
  if (!props.packageInfo || !props.packageInfo.type || !props.packageInfo.price) {
    ElMessage.error('套餐信息不完整，请重试');
    return;
  }
  
  try {
    loading.value = true;
    loadingText.value = '正在生成支付参数...';
    
    const response = await rechargePackage({
      package_type: props.packageInfo.type,
      amount: props.packageInfo.price
    });
    
    if (response.code === 0) {
      const payData = response.data;
      // 判断是否在微信内部浏览器
      const isWechat = /MicroMessenger/i.test(navigator.userAgent);
      
      // 设置订单号便于后续查询
      const currentOrderSn = payData.out_trade_no || '';
      orderSn.value = currentOrderSn;
      
      if (isWechat && payData.appId) {
        // 微信内部浏览器，使用JSAPI支付
        dialogVisible.value = false; // 关闭弹窗，因为JSAPI会有自己的弹窗
        await initWechatJSAPI(payData);
      } else if (payData.mweb_url) {
        // 外部浏览器，使用H5支付
        window.location.href = payData.mweb_url;
        // 开始轮询订单状态
        startCheckOrderStatus(currentOrderSn);
      } else if (payData.code_url) {
        // 二维码支付方式(Native支付)
        qrCodeUrl.value = payData.code_url;
        // 开始轮询订单状态
        startCheckOrderStatus(currentOrderSn);
      } else {
        ElMessage.error('返回的支付参数不完整，请重试');
        emit('error', '返回的支付参数不完整，请重试');
      }
    } else {
      ElMessage.error(response.msg || '创建支付订单失败');
      emit('error', response.msg || '创建支付订单失败');
    }
  } catch (error) {
    console.error('支付失败:', error);
    ElMessage.error('支付失败，请稍后再试');
    emit('error', '支付失败，请稍后再试');
  } finally {
    loading.value = false;
  }
};

// 微信JSAPI支付
const initWechatJSAPI = async (payParams) => {
  // 检查微信环境
  const checkWechatEnv = () => {
    return new Promise((resolve) => {
      if (typeof window.WeixinJSBridge === 'object' && typeof window.WeixinJSBridge.invoke === 'function') {
        resolve();
      } else {
        document.addEventListener('WeixinJSBridgeReady', resolve, false);
      }
    });
  };
  
  // 调用支付
  try {
    await checkWechatEnv();
    
    window.WeixinJSBridge.invoke('getBrandWCPayRequest', {
      appId: payParams.appId,
      timeStamp: payParams.timeStamp,
      nonceStr: payParams.nonceStr,
      package: payParams.package,
      signType: payParams.signType,
      paySign: payParams.paySign
    }, function(res) {
      if (res.err_msg === 'get_brand_wcpay_request:ok') {
        // 支付成功
        paymentStatus.value = { success: true, message: '支付已完成！' };
        ElMessage.success('支付成功！');
        emit('success', { orderSn: orderSn.value });
      } else if (res.err_msg === 'get_brand_wcpay_request:cancel') {
        // 用户取消支付
        paymentStatus.value = { success: false, message: '您取消了支付' };
        ElMessage.info('您取消了支付');
        emit('cancel');
      } else {
        // 支付失败
        paymentStatus.value = { success: false, message: '支付失败，请重试' };
        ElMessage.error('支付失败，请重试');
        emit('error', '支付失败，请重试');
      }
    });
  } catch (error) {
    console.error('微信支付初始化失败:', error);
    ElMessage.error('微信环境尚未准备好，请稍后再试');
    emit('error', '微信环境尚未准备好，请稍后再试');
  }
};

// 开始轮询订单状态
const startCheckOrderStatus = (orderNumber) => {
  if (!orderNumber) {
    console.error('订单编号为空，无法查询订单状态');
    return;
  }
  
  // 清除之前的定时器
  stopOrderCheck();
  
  // 重置检查次数
  checkTimes.value = 0;
  
  // 设置轮询定时器，每3秒查询一次订单状态
  orderTimer.value = setInterval(async () => {
    try {
      checkTimes.value++;
      
      // 超过最大检查次数，停止轮询
      if (checkTimes.value > MAX_CHECK_TIMES) {
        stopOrderCheck();
        paymentStatus.value = { success: false, message: '支付超时，请检查您的支付状态或重新尝试' };
        ElMessage.warning('支付超时，请检查您的支付状态或重新尝试');
        emit('error', '支付超时，请检查您的支付状态或重新尝试');
        return;
      }
      
      // 调用后端接口查询订单状态
      const response = await checkOrderStatus(orderNumber);
      
      if (response.code === 0 && response.data) {
        const orderData = response.data;
        
        // 如果支付成功
        if (orderData.pay_status === 1) {
          // 停止轮询
          stopOrderCheck();
          
          // 更新支付结果和提示
          paymentStatus.value = { success: true, message: '支付已完成！' };
          ElMessage.success('支付成功！');
          
          // 触发成功事件
          emit('success', { orderSn: orderNumber, orderData });
        }
      }
    } catch (error) {
      console.error('检查订单状态失败:', error);
    }
  }, 3000); // 每3秒查询一次
};

// 停止订单检查
const stopOrderCheck = () => {
  if (orderTimer.value) {
    clearInterval(orderTimer.value);
    orderTimer.value = null;
  }
};

// 在组件卸载前清除定时器
onBeforeUnmount(() => {
  stopOrderCheck();
});

// 暴露组件方法
defineExpose({
  showPayment,
  handleClose
});
</script>

<style lang="less" scoped>
.wechat-payment {
  font-family: 'PingFang SC', 'Microsoft YaHei', sans-serif;
}

.payment-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.package-info {
  text-align: center;
  margin-bottom: 24px;
  
  .package-name {
    font-size: 18px;
    font-weight: 500;
    color: #333;
    margin-bottom: 8px;
  }
  
  .package-price {
    font-size: 28px;
    font-weight: 600;
    color: #409EFF;
  }
}

.payment-status {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 16px 0;
  padding: 12px;
  border-radius: 4px;
  width: 100%;
  
  &.success {
    background-color: #f0f9eb;
    color: #67c23a;
  }
  
  &.error {
    background-color: #fef0f0;
    color: #f56c6c;
  }
  
  .el-icon {
    margin-right: 8px;
    font-size: 18px;
  }
}

.qr-code-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  
  p {
    margin-bottom: 16px;
    color: #606266;
  }
  
  .qr-code {
    border: 1px solid #ebeef5;
    padding: 8px;
    box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
    background-color: #fff;
    
    img {
      display: block;
      width: 200px;
      height: 200px;
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-top: 16px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(255, 255, 255, 0.8);
  backdrop-filter: blur(3px);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}

.loading-spinner {
  display: flex;
  flex-direction: column;
  align-items: center;
  background-color: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 8px 24px rgba(0, 0, 0, 0.12);
  
  .el-icon {
    font-size: 36px;
    color: #4dabf7;
    margin-bottom: 16px;
  }
  
  span {
    color: #333;
    font-size: 16px;
    font-weight: 500;
  }
}
</style>
